package com.chen.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * @author Y·C
 * @version 1.0.0
 * @ClassName FileController.java
 * @Description TODO
 * @createTime 2023年04月23日 09:35:00
 */
@Api(tags = "文件上传接口")
@RestController
@RequestMapping("/files")
public class FileController {


    @Value("${file.save.path}")
    private String fileUploadPath;

    @ApiOperation(value = "App图片上传")
    @PostMapping("/upload")
    public String upImgs(HttpServletRequest request,
                         @RequestParam @RequestPart("file") MultipartFile file) throws IOException {
        File fir = new File(fileUploadPath);
        //不存在则创建文件夹
        if (!fir.exists()) {
            fir.mkdirs();
        }
        //文件的后缀名
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        //新文件名字 为了防止重复加上UUID
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
        System.out.println("filesavepath:" + fileUploadPath + "   " + "newFileName:" + newFileName);
        //新的文件路径
        File newFile = new File(fileUploadPath + newFileName);
        //把文件写入新的File文件
        file.transferTo(newFile);
        //url路径=http + :// + server名字 + port端口 + /imges/ + newFileName
        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/files/" + newFileName;
        System.out.println(url);
        return url;
    }

}
